/* eslint-disable consistent-return */
/* eslint-disable func-names */
/* eslint-disable no-return-await */
/* eslint-disable no-async-promise-executor */
import Taro from '@tarojs/taro'
import { getPlatform } from '@UTILS/common'
import i18n from '@I18N'
import { getGlobalData } from './globalData'
const { isWX } = getPlatform()

const isEmptyObject = data => !data || Object.keys(data).length < 1

// Imperial BMI Formula BMI=体重÷身高 2
// const getSingleStepDistance = height => (high - 155.911) / 26.2
const getDistanceByStep = (steps, stepSize = 0.6) => Number((steps * stepSize / 1000).toFixed(1))

const getCalorieByStep = (steps, stepSize = 0.6) => Number((steps * stepSize * 60 * 1.036 / 1000).toFixed(1))

const parse_werun_step_list = (stepInfoList = []) => {
  const datas = stepInfoList.map(item => {
    const { timestamp, step } = item
    return {
      Timestamp: timestamp * 1000,
      Distance: getDistanceByStep(step),
      Step: step,
      Calorie: getCalorieByStep(step)
    }
  })
  return datas
}

export const getWeRunData = async () => {
  try {
    const { cloudID } = await Taro.getWeRunData()
    const { result } = await Taro.cloud.callFunction({
      name: 'openapi',
      data: {
        action: 'getOpenData',
        openData: { list: [cloudID] }
      }
    })
    return parse_werun_step_list(result?.list?.[0].data?.stepInfoList)
  } catch (e) {
    return []
  }
}

export async function getWxUserData() {
  let userData = getGlobalData('userData')
  if (userData) {
    return userData
  }
  try {
    userData = await Taro.getUserInfo()
    return userData
  } catch (err) {
    console.log(err)
    console.log('微信登录或用户接口故障')
    return null
  }
}

export async function checkSettingStatus(scope, { title, content }) {
  let setting = await Taro.getSetting()
  let { authSetting } = setting
  if (!isEmptyObject(authSetting)) {
    if (authSetting[scope] === false) {
      const res = await Taro.showModal({
        title,
        content,
        showCancel: true
      })
      if (res.confirm) {
        setting = await Taro.openSetting()
        authSetting = setting.authSetting
        if (!isEmptyObject(authSetting)) {
          if (authSetting[scope] === true) {
            return await getWxUserData()
          }
        }
      }
    }
  }
  return null
}

let cacheCode = ''
export const getJsCode = async isInit => new Promise(async resolve => {
  let curCode = cacheCode
  if (!curCode || isInit) {
    try {
      const { code } = await Taro.login()
      cacheCode = code
      curCode = code
      resolve(code)
    } catch (error) {
      console.log('Login error: ', error)
      resolve('')
    }
    return
  }
  Taro.checkSession({
    success: () => {
      resolve(curCode)
    },
    fail: async () => {
      const { code } = await Taro.login()
      cacheCode = code
      resolve(code)
    }
  })
})

export const getUserInfo = cloudID => new Promise((resolve, reject) => {
  Taro.cloud.callFunction({
    name: 'openapi',
    data: {
      action: 'getUserInfo',
      cloudID,
    }
  }).then(({ result }) => {
    const userInfo = result?.list?.[0]?.data
    if (!userInfo) return reject(result.errMsg)
    resolve({ unionId: userInfo.unionId, openId: userInfo.openId })
  }).catch(err => {
    reject(err)
  })
})

export const checkMPUpdate = () => {
  if (!isWX) return
  const updateManager = Taro.getUpdateManager()
  updateManager?.onUpdateReady?.(() => {
    Taro.showModal({
      title: i18n.common.update_tip(),
      content: i18n.common.apply_update(),
      success(res) {
        if (res.confirm) {
          updateManager.applyUpdate()
        }
      }
    })
  })
}
